package com.totcy.atom.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.totcy.atom.BuildConfig;
import com.totcy.atom.R;
import com.totcy.atom.adapter.GankTextAdapter;
import com.totcy.atom.bean.BannerBean;
import com.totcy.atom.bean.GankTypeBean;
import com.totcy.atom.presenter.BannerPresenter;
import com.totcy.atom.presenter.GankTypeListPresenter;
import com.totcy.atom.presenter.contract.BannerContract;
import com.totcy.atom.presenter.contract.GankTypeListContract;
import com.totcy.atom.utils.glide.GlideUtil;
import com.totcy.atom.view.activity.WebViewActivity;
import com.totcy.baselibrary.adapter.BaseLoadMoreAdapter;
import com.totcy.baselibrary.adapter.loadmore.OnLoadMoreListener;
import com.totcy.baselibrary.adapter.loadmore.ScollYDistanceListener;
import com.totcy.baselibrary.utils.StatusBarUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * description: 主页新闻
 *
 * @author : Totcy
 *         date: 2017/10/31 17:34
 *         update: 2017/10/31
 * @deprecated 拆分成 HomeNewsTypeFragment 、 GankNewsFragment
 */

public class HomeNewsFragment extends BaseFragment<BannerContract.View, BannerPresenter> implements BannerContract.View, OnLoadMoreListener, OnRefreshListener, BaseLoadMoreAdapter.OnItemClickListener, OnBannerListener, ScollYDistanceListener, GankTypeListContract.View {

    @BindView(R.id.recyclerView)
    RecyclerView rvImage;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private int pageNum = 1;
    private static final int pageSize = 15;
    private GankTextAdapter adapter;
    private List<GankTypeBean> list = new ArrayList<>();
    private List<BannerBean> images = new ArrayList<>();
    private static final String type = "Android";
    private Banner banner;

    private GankTypeListPresenter gankTypeListPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home_news;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        gankTypeListPresenter = new GankTypeListPresenter(getActivity());
        gankTypeListPresenter.attachView(this);

        //fragment自己适配 toolbar 增加title layout paddingTop
        StatusBarUtil.setPaddingSmart(getActivity(), toolbar);
        toolbar.setAlpha(0f);

        LinearLayoutManager lm = new LinearLayoutManager(getActivity());
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        rvImage.setLayoutManager(lm);

        //banner set
        adapter = new GankTextAdapter(getActivity(), list, initBanner());
        rvImage.setAdapter(adapter);

        adapter.setOnLoadMoreListener(rvImage, this);
        adapter.setScrollYDistanceListener(this);
        adapter.setOnItemClickListener(this);
        //设置回弹动画插值器 减速效果
        refresh.setReboundInterpolator(new DecelerateInterpolator());
        refresh.setOnRefreshListener(this);
        //自动刷新
        refresh.autoRefresh(200);
    }

    /**
     * banner初始化
     */
    private View initBanner() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.header_banner_news, null);
        banner = view.findViewById(R.id.bannerView);
        //设置banner样式 标题 圆形指示器水平显示
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //圆形指示器居右
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //设置图片加载器
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                BannerBean bannerBean = (BannerBean) path;
                GlideUtil.loadImage(getActivity(), bannerBean.getImage_url(), imageView);
            }
        });
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Accordion);
        banner.setOnBannerListener(this);
        return view;
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        getPresenter().getBannerList();
        pageNum = 1;
        gankTypeListPresenter.getGankTypeData(type, pageSize, pageNum);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        gankTypeListPresenter.getGankTypeData(type, pageSize, pageNum);
    }

    @Override
    public void onClickLoadMore() {
        gankTypeListPresenter.getGankTypeData(type, pageSize, pageNum);
    }

    @Override
    public void onGankTypeData(List<GankTypeBean> images) {
        refresh.finishRefresh(true);

        if (pageNum == 1) {
            list.clear();
        }
        list.addAll(images);
        adapter.notifyDataSetChanged();
        adapter.setLoadMoreFinish(images.size() == pageSize);
    }

    @Override
    public void onDataFail() {
        adapter.setLoadFail();
        refresh.finishRefresh(false);
    }

    @Override
    public void onItemClick(int position) {
        Bundle bundle = new Bundle();
        bundle.putString("url", list.get(position).getUrl());
        bundle.putString("title", list.get(position).getDesc());
        if (list.get(position).getImages() != null && list.get(position).getImages().size() > 0) {
            bundle.putString("thumbUrl", list.get(position).getImages().get(0));
        }
        openActivity(WebViewActivity.class, bundle);
    }

    @Override
    public void OnBannerClick(int position) {
        Bundle bundle = new Bundle();
        bundle.putString("url", images.get(0).getAction_url());
        bundle.putString("title", BuildConfig.APP_NAME);
        openActivity(WebViewActivity.class, bundle);
    }


    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @Override
    public void onBannerData(final List<BannerBean> images) {
        this.images.clear();
        this.images.addAll(images);
        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> e) throws Exception {
                List<String> list = new ArrayList<String>();
                for (BannerBean bannerBean : images) {
                    list.add(bannerBean.getDescription());
                }
                e.onNext(list);
            }
        })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(@NonNull List<String> s) throws Exception {
                        //设置图片集合
                        banner.setImages(images);
                        //设置标题集合（当banner样式有显示title时）
                        banner.setBannerTitles(s);
                        //banner设置方法全部调用完毕时最后调用
                        banner.start();
                    }
                });
    }

    @Override
    public void onScrolledY(int dy) {
        int minScrollHeight = 200;
        changeToolbarAlpha(dy < minScrollHeight);
    }

    private boolean isOver = false;

    /**
     * 切换toolbar背景
     *
     * @param isTransparent
     */
    private void changeToolbarAlpha(boolean isTransparent) {

        if (isOver == isTransparent) {
            //避免多次执行
            isOver = !isTransparent;
            toolbar.clearAnimation();
            toolbar.animate().alpha(isTransparent ? 0f : 1f)
                    .setDuration(1000)
                    .setInterpolator(new DecelerateInterpolator())
                    .start();
        }

    }

}

